package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.code.RedisCode;
import one.stand.entity.OrderNoEntity;
import one.stand.entity.WxNoticeEntity;
import one.stand.enums.LoginEnum;
import one.stand.enums.OrderStateEnum;
import one.stand.enums.RefundStateEnum;
import one.stand.enums.WxNoticeEnums;
import one.stand.exception.GoPayException;
import one.stand.model.*;
import one.stand.request.*;
import one.stand.response.OrdersResponse;
import one.stand.response.ShopcartResponse;
import one.stand.service.OrdersService;
import one.stand.service.WxMessageService;
import one.stand.service.WxPayService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Service
public class OrdersServiceImpl extends PublicBaseService implements OrdersService {
    @Autowired
    WxPayService wxPayService;

    @Autowired
    protected WxMessageService wxMessageService;

    @Override
    public ResultModel selectShopcart(ShopcartRequest shopcartRequest) {
        ShopcartModel shopcartModel = new ShopcartModel();
        if (shopcartRequest != null) {
            BeanUtils.copyProperties(shopcartRequest, shopcartModel);
        }
        shopcartModel.setUserId(shopcartRequest.getId().intValue());
        shopcartModel.setCreateTime(currentDate());
        List<ShopcartModel> list = shopcartMapper.selectShopcart(shopcartModel);
        if (list == null || list.size() < 1) {
            return ResultModel.noData();
        }
        List<ShopcartResponse> shopcartResponseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                ShopcartResponse shopcartResponse = new ShopcartResponse();
                BeanUtils.copyProperties(obj, shopcartResponse);
                shopcartResponseList.add(shopcartResponse);
            }
        });
        return ResultModel.success(shopcartResponseList);
    }

    @Override
    public ResultModel addShopcart(ShopcartRequest request) {
        log.info("添加购物车：{}", JSON.toJSONString(request));
        if(request == null || request.getId() == null || request.getCardId() == null || request.getGoodsId() == null || request.getSpecId() == null){
            return ResultModel.checkParamFail();
        }
        if(request.getNum() == null || request.getNum() <= 0){
            return ResultModel.fail("请选择商品数量~！");
        }
        // 判断商品规格库存
        GoodSpecModel goodSpecModel = goodSpecMapper.selectByPrimaryKey(request.getSpecId());
        if (goodSpecModel == null || goodSpecModel.getSpecNum() == null || goodSpecModel.getCompanyId() == null) {
            return ResultModel.fail("商品规格失效，请重新筛选~！");
        }
        if (goodSpecModel.getSpecNum() < request.getNum()) {
            return ResultModel.fail("库存不足~！");
        }
        ShopcartModel shopcartModel = shopcartMapper.selectShopcartSpec(new ShopcartModel(){{
            setUserId(request.getId().intValue());
            setSpecId(request.getSpecId());
        }});
        // 有相同规格购物车记录，就修改购物车商品数量
        if (shopcartModel != null && shopcartModel.getShopCartId() > 0) {
            shopcartModel.setNum(request.getNum() + shopcartModel.getNum());
            shopcartModel.setForwardId(request.getForwardId());
            shopcartMapper.updateByPrimaryKeySelective(shopcartModel);
            return ResultModel.success("保存成功~!");
        } else {
            // 新增购物车
            shopcartModel = new ShopcartModel();
            BeanUtils.copyProperties(request, shopcartModel);
            shopcartModel.setUserId(request.getId().intValue());
            shopcartModel.setCompanyId(goodSpecModel.getCompanyId());
            shopcartModel.setCreateTime(currentDate());
            shopcartModel.setForwardId(request.getForwardId());
            shopcartModel.setIsDel(0);
            shopcartMapper.insertSelective(shopcartModel);
            return ResultModel.success("保存成功");
        }
    }

    @Override
    public ResultModel delShopcart(ShopcartRequest shopcartRequest) {
        if (shopcartMapper.deleteShopcart(shopcartRequest.getShopCartIds().split(",")) > 0) {
            return ResultModel.success("删除成功");
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel updShopcartNum(ShopcartRequest shopcartRequest) {
        ShopcartModel shopcartModel = new ShopcartModel();
        if (shopcartRequest != null) {
            BeanUtils.copyProperties(shopcartRequest, shopcartModel);
        }
        if (shopcartRequest.getNum() <= 0) {
            return ResultModel.fail("购买数量必须大于1");
        }
        if (shopcartMapper.updShopcartNum(shopcartModel) > 0) {
            return ResultModel.success("修改成功");
        }
        return ResultModel.fail();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel directOrder(OrderinfoRequest orderinfoRequest) {
        log.info("商品直接下单：{}", JSON.toJSONString(orderinfoRequest));
        // 判断商品规格库存
        GoodSpecModel goodSpecModel = goodSpecMapper.selectByPrimaryKey(orderinfoRequest.getSpecId());
        if (goodSpecModel == null) {
            log.info("商品规格失效，请重新筛选！:", orderinfoRequest);
            return ResultModel.fail("商品规格失效，请重新筛选！");
        }
        if (goodSpecModel.getSpecNum() < orderinfoRequest.getNum()) {
            log.info("库存不足！:", orderinfoRequest);
            return ResultModel.fail("库存不足！");
        }
        // 在添加订单表
        OrdersModel ordersModel = new OrdersModel();
        // 用户ID
        ordersModel.setUserId(orderinfoRequest.getId().intValue());
        // 订单总金额
        ordersModel.setOrderPrice(orderinfoRequest.getAllPrice() * orderinfoRequest.getNum());
        // 默认线上支付
        ordersModel.setPayType(1);
        ordersModel.setCreateTime(new Date());
        // 订单状态（1待付款，2待发货，3待收货，4已完成，5交易取消，6退款成功）
        ordersModel.setOrderState(OrderStateEnum.WAIT_PAYMENT.getCode());
        // 1未申请，2退款申请中，3退款成功
        ordersModel.setRefundState(RefundStateEnum.NO_REFUND.getCode());
        ordersModel.setCompanyId(goodSpecModel.getCompanyId());
        // 订单号
        ordersModel.setOrdersNo(getOrderNo());
        // 配送方式
        ordersModel.setDeliveryType(1);
        // 配送状态
        ordersModel.setDeliveryState(1);
        if (ordersMapper.insertSelective(ordersModel) > 0) {
            // 添加订单明细表
            OrderinfoModel model = new OrderinfoModel();
            // 订单id
            model.setOrdersId(ordersModel.getOrdersId());
            model.setGoodsId(goodSpecModel.getGoodsId());
            model.setSpecId(goodSpecModel.getSpecId());
            model.setNum(orderinfoRequest.getNum());
            model.setPrice(goodSpecModel.getPrice());
            // 订单价格
            model.setAllPrice(goodSpecModel.getPrice() * orderinfoRequest.getNum());
            model.setCreateTime(new Date());
            model.setCardId(orderinfoRequest.getCardId());
            model.setForwardId(orderinfoRequest.getForwardId());
            orderinfoMapper.insertSelective(model);
            // 发送新订单微信推送提醒
            List<WxNoticeEntity> listMap = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
                setType(1);
                setOrdersId(ordersModel.getOrdersId());
            }});
            listMap.forEach(entity -> {
                {
                    String[] fillData = {ordersModel.getOrdersNo(), getLimitGoodsName(entity.getGoodsName()), getMoneyString(orderinfoRequest.getAllPrice()) + "元", getDay(), entity.getReceiveName()};
                    wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.NEW_ORDER.getCode(), fillData, LoginEnum.CRM.getAccountType(),entity.getCrmCompanyId());
                }
            });
            return ResultModel.success(ordersModel.getOrdersId());
        }
        log.info("下单失败！:", orderinfoRequest);
        return ResultModel.fail("下单失败");
    }

    @Override
    public ResultModel<List<OrdersResponse>> getOrderList(OrdersRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        OrdersModel ordersModel = new OrdersModel();
        BeanUtils.copyProperties(request, ordersModel);
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        BeanUtils.copyProperties(request, ordersModel);
        ordersModel.setUserId(request.getId().intValue());
        List<OrdersModel> list = ordersMapper.getOrderList(ordersModel);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<OrdersResponse> ordersResponseArrayList = new ArrayList<>();
        list.forEach(obj -> {
            {
                OrdersResponse response = new OrdersResponse();
                BeanUtils.copyProperties(obj, response);
                if(obj.getDeliveryTime() != null) {
                    response.setDeliveryTimes(getSurplusDeliveryTime(obj.getDeliveryTime()));
                }
                ordersResponseArrayList.add(response);
            }
        });
        PageInfo<OrdersResponse> pageInfo = new PageInfo<>(ordersResponseArrayList);
        return ResultModel.success(pageInfo.getList());
    }

    @Override
    public ResultModel<List<Map<String, Object>>> getOrderListCount(OrdersRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        OrdersModel ordersModel = new OrdersModel();
        ordersModel.setUserId(request.getId().intValue());
        List<Map<String, Object>> list = ordersMapper.getOrderListCount(ordersModel);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        return ResultModel.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String paymentOrders(String notifyData) {
        log.info("微信回调参数：{}", notifyData);
        Map<String, String> notifyMap;
        try {
            notifyMap = wxPayService.payCallback(notifyData);
            log.info("进行微信回调验证：{}", notifyMap);
            if (notifyMap != null) {
                // 更具订单编号获取redis下保存的订单信息
                String outTradeNo = notifyMap.get("out_trade_no");
                OrderNoEntity entity = redisUtil.get(RedisCode.getUserOrderKey(outTradeNo));
                if (entity == null) {
                    log.info("微信支付回调，redis中无支付订单id", notifyData);
                    return wxPayService.fail();
                }
                // 微信回调金额和本地redis保存金额验证
                String totalFee = notifyMap.get("total_fee");
                if (Integer.parseInt(totalFee) != entity.getMoney()) {
                    log.info("微信支付回调，订单金额异常", notifyData);
                    return wxPayService.fail();
                }
                // 具体下单的商品信息 验证
                List<OrderinfoModel> list = orderinfoMapper.selectOrderInfoNum(entity.getOrdersId());
                if (list == null || list.size() <= 0) {
                    log.info("微信支付回调，订单信息异常", notifyData);
                    return wxPayService.fail();
                }
                // 删除redis里缓存的订单信息
                redisUtil.remove(RedisCode.getUserOrderKey(outTradeNo));
                /**
                 * 付款成功
                 * */
                if (PublicBaseService.SUCCESS.equals(notifyMap.get("return_code"))) {
                    // 修改商品库存
                    for (OrderinfoModel orderinfoModel : list) {
                        GoodSpecModel goodSpecModel = new GoodSpecModel();
                        goodSpecModel.setSpecNum(orderinfoModel.getNum());
                        goodSpecModel.setSpecId(orderinfoModel.getSpecId());
                        goodSpecMapper.updateGoodSpecNum(goodSpecModel);
                    }
                    // 修改订单状态
                    OrdersModel model = new OrdersModel();
                    model.setOrderState(OrderStateEnum.WAIT_DELIVER.getCode());
                    model.setTradeNo(outTradeNo);
                    model.setPayPrice(entity.getMoney());
                    model.setPayTime(currentDate());
                    model.setOrdersId(entity.getOrdersId());
                    ordersMapper.updateByPrimaryKeySelective(model);
                    // 更新拼团信息
                    if(entity.getAssembleId() != null){
                        assemble(entity.getAssembleId());
                    }
                    // 微信推送给用户支付成功模板信息
                    WxNoticeEntity wxNoticeEntity = orderinfoMapper.selectOrderBackInfo(new OrderinfoModel(){{
                        setOrdersId(entity.getOrdersId());
                    }});
                    String[] fillData = {outTradeNo, wxNoticeEntity.getGoodsName(), getMoneyString(totalFee) + "元", wxNoticeEntity.getPayDate()};
                    wxMessageService.sendTemplate(wxNoticeEntity.getUserOpenId(), redisUtil.get(RedisCode.getPrepayId(outTradeNo)), WxNoticeEnums.ORDER_PAY_SUCCESS.getCode(), fillData, LoginEnum.USER.getAccountType(),wxNoticeEntity.getCompanyId());
                    // 删除redis里缓存的订单prepayId
                    redisUtil.remove(RedisCode.getPrepayId(outTradeNo));
                    // 订单状态改变 微信推送模板信息
                    List<WxNoticeEntity> listMap = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
                        setOrdersId(entity.getOrdersId());
                        setType(1);
                    }});
                    listMap.forEach(entity1 -> {{
                            String[] fillData1 = {outTradeNo, wxNoticeEntity.getGoodsName(), getMoneyString(totalFee) + "元", OrderStateEnum.WAIT_DELIVER.getMessage(), entity1.getRemark()};
                            wxMessageService.sendTemplate(entity1.getCrmOpenId(), entity1.getCrmFormId(), WxNoticeEnums.ORDER_STATE_CRM.getCode(), fillData1, LoginEnum.CRM.getAccountType(),entity1.getCrmCompanyId());
                    }});
                } else {
                    // 微信推送失败信息
                    WxNoticeEntity wxNoticeEntity = orderinfoMapper.selectOrderBackInfo(new OrderinfoModel(){{
                        setOrdersId(entity.getOrdersId());
                    }});
                    String[] fillData = {outTradeNo, wxNoticeEntity.getGoodsName(), getMoneyString(totalFee) + "元", getDay(), notifyMap.get("return_msg")};
                    wxMessageService.sendTemplate(wxNoticeEntity.getUserOpenId(), redisUtil.get(RedisCode.getPrepayId(outTradeNo)), WxNoticeEnums.ORDER_PAY_FAIL.getCode(), fillData, LoginEnum.USER.getAccountType(),wxNoticeEntity.getCompanyId());
                    // 删除redis里缓存的订单prepayId
                    redisUtil.remove(RedisCode.getPrepayId(outTradeNo));
                }
                // 添加用户支付记录信息
                PaymentRecordModel paymentRecordModel = new PaymentRecordModel();
                paymentRecordModel.setUserId(entity.getUserId());
                paymentRecordModel.setAppid(notifyMap.get("appid"));
                paymentRecordModel.setMchId(notifyMap.get("mch_id"));
                paymentRecordModel.setOpenid(notifyMap.get("openid"));
                paymentRecordModel.setOutTradeNo(outTradeNo);
                paymentRecordModel.setResultCode(notifyMap.get("result_code"));
                paymentRecordModel.setSign(notifyMap.get("sign"));
                paymentRecordModel.setTimeEnd(notifyMap.get("time_end"));
                paymentRecordModel.setTotalFee(Integer.parseInt(totalFee));
                paymentRecordModel.setTradeNo(outTradeNo);
                paymentRecordModel.setTradeType(notifyMap.get("trade_type"));
                paymentRecordModel.setTransactionId(notifyMap.get("transaction_id"));
                paymentRecordModel.setCreateTime(currentDate());
                paymentRecordMapper.insertSelective(paymentRecordModel);
                return wxPayService.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("微信回调验证错误", e);
        }
        return wxPayService.fail();
    }

    /**
     * 拼团信息更新
     */
    @Async("asyncServiceExecutor")
    public void assemble(Integer assembleId){
        if(assembleId == null){
            return;
        }
        AssembleModel model = assembleMapper.selectByPrimaryKey(assembleId);
        if(model == null){
            return;
        }
        model.setPutAssemble(model.getPutAssemble() + 1);
        if(model.getAssembleNum() != null && model.getAssembleNum().equals(model.getPutAssemble())){
            model.setState(2);
        }else{
            model.setState(1);
        }
        assembleMapper.updateByPrimaryKeySelective(model);
    }

    /**
     * 分销金额提成 (确认收货时调用)
     * */
    @Override
    @Async("asyncServiceExecutor")
    public void companyRoyalty(Integer ordersId, String ip, String companyKey) {
        if( ordersId == null || StringUtils.isBlank(companyKey)){
            return;
        }
        try {
            // 根据订单查询订单商品详情
            List<OrderinfoModel> list = orderinfoMapper.selectComanyRoyalty(ordersId);
            if(list == null || list.size() <= 0){
                return;
            }
            // 总提成金额
            Integer amount = 0;
            // 分销提成
            for(OrderinfoModel model : list) {
                boolean fal = model.getForwardId() != null && model.getAllPrice() > 0 && model.getRoyaltyRatio() > 0;
                if (fal) {
                    RoyaltyRecordModel royaltyRecordModel = new RoyaltyRecordModel();
                    // 提现订单号
                    String recordNo = getRecordNo();
                    Integer money = model.getAllPrice() * model.getRoyaltyRatio() / 100;
                    // 微信提现操作
                    ResultModel resultModel = wxPayService.doCash(recordNo, model.getOpenId(), money, ip, companyKey);
                    royaltyRecordModel.setRecordNo(recordNo);
                    royaltyRecordModel.setOrderMoney(model.getAllPrice());
                    royaltyRecordModel.setRoyaltyMoney(money);
                    royaltyRecordModel.setUserId(model.getUserId());
                    royaltyRecordModel.setCreateTime(currentDate());
                    royaltyRecordModel.setIsDel(0);
                    royaltyRecordModel.setLevel(model.getLevel());
                    royaltyRecordModel.setType(1);
                    royaltyRecordModel.setCompanyId(model.getCompanyId());
                    royaltyRecordModel.setOrdersId(model.getOrderInfoId());
                    if(resultModel.isSuccess()){
                        royaltyRecordModel.setState(1);
                    }else{
                        royaltyRecordModel.setState(0);
                        royaltyRecordModel.setRemark(resultModel.getMessage());
                    }
                    // 保存分销金额记录
                    royaltyRecordMapper.insertSelective(royaltyRecordModel);
                    // 累计提成金额
                    amount += money;
                }
            }
            // 商城公司拥有人提现
            OrderinfoModel orderinfoModel = list.get(0);
            CompanyTransferModel companyTransferModel = new CompanyTransferModel();
            // 提现订单号
            String transferNo = getRecordNo();
            Integer money = orderinfoModel.getPayPrice() - amount;
            // 微信提现操作
            ResultModel resultModel = wxPayService.doCash(transferNo, orderinfoModel.getCompanyOpenId(), money, ip, companyKey);
            companyTransferModel.setTransferNo(transferNo);
            companyTransferModel.setOrderAmount(orderinfoModel.getPayPrice());
            companyTransferModel.setRoyaltyAmount(amount);
            companyTransferModel.setTransferAmount(money);
            companyTransferModel.setUserId(orderinfoModel.getCompanyUserId());
            companyTransferModel.setCreateTime(currentDate());
            companyTransferModel.setIsDel(0);
            companyTransferModel.setCompanyId(orderinfoModel.getCompanyId());
            companyTransferModel.setOrdersId(ordersId);
            if(resultModel.isSuccess()){
                companyTransferModel.setState(1);
            }else{
                companyTransferModel.setState(0);
                companyTransferModel.setRemark(resultModel.getMessage());
            }
            // 保存分销金额记录
            companyTransferMapper.insertSelective(companyTransferModel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 分销金额提成 (确认收货时调用) （3.2版本迭代）
     * */
    @Override
    @Async("asyncServiceExecutor")
    public void companyRoyaltyNew(Integer ordersId, String ip, String companyKey) {
        if(ordersId == null || StringUtils.isBlank(companyKey)){
            return;
        }
        try {
            // 根据订单查询订单商品详情
            List<OrderinfoModel> list = orderinfoMapper.selectComanyRoyaltyNew(ordersId);
            if(list == null || list.size() <= 0){
                return;
            }
            // 总提成金额
            Integer amount = 0;
            // 订单分销提成
            for(OrderinfoModel model : list) {
                // 判断转发人是否是有效的一级分销员
                boolean fat = false;
                // 一级分销提成
                boolean fal = model.getOneUserId() != null && model.getAllPrice() > 0;
                if (fal) {
                    OrderinfoModel orderinfoModel1 = new OrderinfoModel();
                    orderinfoModel1.setUserId(model.getOneUserId());
                    orderinfoModel1.setCompanyId(model.getCompanyId());
                    OrderinfoModel orderinfoModel = orderinfoMapper.getForwardUserId(orderinfoModel1);
                    if(orderinfoModel != null){
                        fat = true;
                        // 提现订单号
                        String recordNo = getRecordNo();
                        RoyaltyRecordModel royaltyRecordModel = new RoyaltyRecordModel();
                        Integer money = model.getAllPrice() * orderinfoModel.getOneRoyalty() / 100;
                        ResultModel resultModel = wxPayService.doCash(recordNo, orderinfoModel.getOpenId(), money, ip, companyKey);
                        royaltyRecordModel.setRecordNo(recordNo);
                        royaltyRecordModel.setOrderMoney(model.getAllPrice());
                        royaltyRecordModel.setRoyaltyMoney(money);
                        royaltyRecordModel.setUserId(model.getOneUserId());
                        royaltyRecordModel.setCreateTime(currentDate());
                        royaltyRecordModel.setIsDel(0);
                        royaltyRecordModel.setLevel(1);
                        royaltyRecordModel.setType(1);
                        royaltyRecordModel.setCompanyId(model.getCompanyId());
                        royaltyRecordModel.setOrdersId(model.getOrderInfoId());
                        if(resultModel.isSuccess()){
                            royaltyRecordModel.setState(1);
                        }else{
                            royaltyRecordModel.setState(0);
                            royaltyRecordModel.setRemark(resultModel.getMessage());
                        }
                        // 保存分销金额记录
                        royaltyRecordMapper.insertSelective(royaltyRecordModel);
                        // 累计提成金额
                        amount += money;
                    }
                }
                // 二级分销提成
                boolean fla = model.getTwoUserId() != null && model.getAllPrice() > 0;
                if (fla) {
                    OrderinfoModel orderinfoModel1 = new OrderinfoModel();
                    orderinfoModel1.setUserId(model.getTwoUserId());
                    orderinfoModel1.setCompanyId(model.getCompanyId());
                    OrderinfoModel orderinfoModel = orderinfoMapper.getForwardUserId(orderinfoModel1);
                    if(orderinfoModel != null){
                        // 提现订单号
                        String recordNo = getRecordNo();
                        RoyaltyRecordModel royaltyRecordModel = new RoyaltyRecordModel();
                        Integer money = model.getAllPrice() * (fat ? orderinfoModel.getTwoRoyalty() : orderinfoModel.getOneRoyalty()) / 100;
                        ResultModel resultModel = wxPayService.doCash(recordNo, orderinfoModel.getOpenId(), money, ip, companyKey);
                        royaltyRecordModel.setRecordNo(recordNo);
                        royaltyRecordModel.setOrderMoney(model.getAllPrice());
                        royaltyRecordModel.setRoyaltyMoney(money);
                        royaltyRecordModel.setUserId(model.getTwoUserId());
                        royaltyRecordModel.setCreateTime(currentDate());
                        royaltyRecordModel.setIsDel(0);
                        royaltyRecordModel.setLevel(fat ? 2 : 1);
                        royaltyRecordModel.setType(1);
                        royaltyRecordModel.setCompanyId(model.getCompanyId());
                        royaltyRecordModel.setOrdersId(model.getOrderInfoId());
                        if(resultModel.isSuccess()){
                            royaltyRecordModel.setState(1);
                        }else{
                            royaltyRecordModel.setState(0);
                            royaltyRecordModel.setRemark(resultModel.getMessage());
                        }
                        // 保存分销金额记录
                        royaltyRecordMapper.insertSelective(royaltyRecordModel);
                        // 累计提成金额
                        amount += money;
                    }
                }
            }
            // 商城公司拥有人提现
            OrderinfoModel orderinfoModel = list.get(0);
            CompanyTransferModel companyTransferModel = new CompanyTransferModel();
            // 提现订单号
            String transferNo = getRecordNo();
            Integer money = orderinfoModel.getPayPrice() - amount;
            // 微信提现操作
            ResultModel resultModel = wxPayService.doCash(transferNo, orderinfoModel.getCompanyOpenId(), money, ip, companyKey);
            companyTransferModel.setTransferNo(transferNo);
            companyTransferModel.setOrderAmount(orderinfoModel.getPayPrice());
            companyTransferModel.setRoyaltyAmount(amount);
            companyTransferModel.setTransferAmount(money);
            companyTransferModel.setUserId(orderinfoModel.getCompanyUserId());
            companyTransferModel.setCreateTime(currentDate());
            companyTransferModel.setIsDel(0);
            companyTransferModel.setCompanyId(orderinfoModel.getCompanyId());
            companyTransferModel.setOrdersId(ordersId);
            if(resultModel.isSuccess()){
                companyTransferModel.setState(1);
            }else{
                companyTransferModel.setState(0);
                companyTransferModel.setRemark(resultModel.getMessage());
            }
            // 保存分销金额记录
            companyTransferMapper.insertSelective(companyTransferModel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public ResultModel<Map<String, String>> goPay(OrdersRequest request) {
        log.info("去支付：{}", JSON.toJSONString(request));
        if (request == null || request.getOrdersId() == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getAddressId() == null) {
            log.info("请选择收货地址！", request);
            return ResultModel.fail("请选择收货地址！");
        }
        List<OrderinfoModel> list = orderinfoMapper.selectOrderInfoNum(request.getOrdersId());
        if(list == null ||  list.size() <= 0){
            log.info("商品规格信息异常！", request);
            return ResultModel.fail("商品规格信息异常！");
        }
        for(OrderinfoModel model : list){
            if(model.getNum() > model.getSpecNum()){
                log.info("商品库存不足！", request);
                return ResultModel.fail("商品库存不足！");
            }
        }
        // 查询订单信息
        OrdersModel ordersModel = ordersMapper.getGoPayOrderInfo(new OrdersModel(){{
            setOrdersId(request.getOrdersId());
        }});
        // 判断订单状态
        if (ordersModel == null || ordersModel.getOrderPrice() <= 0
                || !OrderStateEnum.WAIT_PAYMENT.getCode().equals(ordersModel.getOrderState())
                || !RefundStateEnum.NO_REFUND.getCode().equals(ordersModel.getRefundState())) {
            log.info("无效支付信息！", request);
            return ResultModel.fail("无效支付信息，请联系客户~！");
        }
        try {
            // 添加收货地址
            OrdersModel model = new OrdersModel();
            model.setAddressId(request.getAddressId());
            model.setRemark(request.getRemark());
            model.setOrdersId(request.getOrdersId());
            ordersMapper.updateOrderAddress(model);
            // redis保存下单商品信息
            OrderNoEntity entity = new OrderNoEntity();
            entity.setOrdersId(request.getOrdersId());
            entity.setUserId(request.getId().intValue());
            entity.setMoney(ordersModel.getOrderPrice());
            entity.setCompanyId(ordersModel.getCompanyId());
            redisUtil.set(RedisCode.getUserOrderKey(ordersModel.getOrdersNo()), entity, 30, TimeUnit.MINUTES);
            // 查询用户openId信息
            UserModel userModel = userMapper.selectByPrimaryKey(request.getId().intValue());
            // 调用微信支付生产二维码接口
            Map<String, String> wxData = wxPayService.wxPay(body, ordersModel.getOrdersNo(), String.valueOf(ordersModel.getOrderPrice()), userModel.getOpenId(), request.getIp(), request.getOrdersId(), request.getCompanyKey());
            // 微信生成的预支付会话标识，用于后续接口调用中使用（微信推送模板），该值有效期为2小时
            redisUtil.set(RedisCode.getPrepayId(ordersModel.getOrdersNo()), wxData.get("prepay_id"), 120, TimeUnit.MINUTES);
            return ResultModel.success(wxData);
        } catch (GoPayException gpe) {
            log.info(gpe.getMessage());
            return ResultModel.fail(gpe.getMessage());
        } catch (Exception e) {
            log.info("支付请求失败：" + e.getMessage());
            return ResultModel.fail(e.getMessage());
        }
    }

    @Override
    public ResultModel<Map<String, String>> goPayNew(OrdersRequest request) {
        log.info("提交订单：{}", JSON.toJSONString(request));
        /** 3.2版本 拼团版本 */
        ResultModel resultModel = validationOrderParamesNew(request);
        if(!resultModel.isSuccess()){
            return resultModel;
        }
        try {
            Map<String, Object> map = (Map<String, Object>)resultModel.getData();
            // 添加订单表
            OrdersModel ordersModel = new OrdersModel();
            ordersModel.setUserId(request.getId().intValue());
            ordersModel.setOrderPrice((int)map.get("orderPrice"));
            ordersModel.setPayType(1);
            ordersModel.setCreateTime(currentDate());
            ordersModel.setOrderState(OrderStateEnum.WAIT_PAYMENT.getCode());
            ordersModel.setRefundState(RefundStateEnum.NO_REFUND.getCode());
            ordersModel.setCompanyId((int)map.get("companyId"));
            ordersModel.setOrdersNo(getOrderNo());
            ordersModel.setDeliveryType(1);
            ordersModel.setDeliveryState(1);
            ordersModel.setAddressId(request.getAddressId());
            ordersModel.setRemark(request.getRemark());
            ordersModel.setAssembleId(request.getAssembleId());
            if (ordersMapper.insertSelective(ordersModel) > 0) {
                List<GoodSpecModel> list = (List<GoodSpecModel>)map.get("list");
                for(GoodSpecModel goodSpecModel : list){
                    // 添加订单明细表
                    OrderinfoModel model = new OrderinfoModel();
                    model.setOrdersId(ordersModel.getOrdersId());
                    model.setGoodsId(goodSpecModel.getGoodsId());
                    model.setSpecId(goodSpecModel.getSpecId());
                    model.setNum(goodSpecModel.getNum());
                    model.setPrice(goodSpecModel.getPrice());
                    model.setAllPrice(goodSpecModel.getPrice() * goodSpecModel.getNum());
                    model.setCreateTime(currentDate());
                    model.setCardId(goodSpecModel.getCardId());
                    model.setForwardId(goodSpecModel.getForwardId());
                    model.setLevel(goodSpecModel.getLevel());
                    orderinfoMapper.insertSelective(model);
                    // 如果购物车shopCartId 不为空，删除购物车信息
                    if(goodSpecModel.getShopCartId() != null && goodSpecModel.getShopCartId() > 0) {
                        shopcartMapper.deleteByPrimaryKey(goodSpecModel.getShopCartId());
                    }
                }
            }
            // redis保存下单商品信息
            OrderNoEntity entity = new OrderNoEntity();
            entity.setOrdersId(ordersModel.getOrdersId());
            entity.setUserId(request.getId().intValue());
            entity.setMoney(ordersModel.getOrderPrice());
            entity.setCompanyId(ordersModel.getCompanyId());
            entity.setAssembleId(request.getAssembleId());
            redisUtil.set(RedisCode.getUserOrderKey(ordersModel.getOrdersNo()), entity, 30, TimeUnit.MINUTES);
            // 查询用户openId信息
            UserModel userModel = userMapper.selectByPrimaryKey(request.getId().intValue());
            // 调用微信支付生产二维码接口
            Map<String, String> wxData = wxPayService.wxPay(body, ordersModel.getOrdersNo(), String.valueOf(ordersModel.getOrderPrice()), userModel.getOpenId(), request.getIp(), ordersModel.getOrdersId(), request.getCompanyKey());
            // 微信生成的预支付会话标识，用于后续接口调用中使用（微信推送模板），该值有效期为2小时
            redisUtil.set(RedisCode.getPrepayId(ordersModel.getOrdersNo()), wxData.get("prepay_id"), 120, TimeUnit.MINUTES);
            // 发送新订单微信推送提醒
            List<WxNoticeEntity> listMap = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
                setType(1);
                setOrdersId(ordersModel.getOrdersId());
            }});
            listMap.forEach(obj -> {{
                String[] fillData = {ordersModel.getOrdersNo(), getLimitGoodsName(obj.getGoodsName()), getMoneyString(ordersModel.getOrderPrice()) + "元", getDay(), obj.getReceiveName()};
                wxMessageService.sendTemplate(obj.getCrmOpenId(), obj.getCrmFormId(), WxNoticeEnums.NEW_ORDER.getCode(), fillData, LoginEnum.CRM.getAccountType(), obj.getCrmCompanyId());
            }});
            return ResultModel.success(wxData);
        } catch (GoPayException gpe) {
            log.info(gpe.getMessage());
            return ResultModel.fail(gpe.getMessage());
        } catch (Exception e) {
            log.info("支付请求失败：" + e.getMessage());
            return ResultModel.fail(e.getMessage());
        }
    }

    @Override
    public ResultModel<Map<String, String>> goTwoPay(OrdersRequest request) {
        log.info("去支付（下单未支付后再次支付）：{}", JSON.toJSONString(request));
        if (request == null || request.getOrdersId() == null) {
            return ResultModel.checkParamFail();
        }
        List<OrderinfoModel> list = orderinfoMapper.selectOrderInfoNum(request.getOrdersId());
        if(list == null ||  list.size() <= 0){
            return ResultModel.fail("商品规格信息异常！");
        }
        for(OrderinfoModel model : list){
            if(model.getNum() > model.getSpecNum()){
                return ResultModel.fail("商品库存不足！");
            }
        }
        // 查询订单信息
        OrdersModel ordersModel = ordersMapper.getGoPayOrderInfo(new OrdersModel(){{
            setOrdersId(request.getOrdersId());
        }});
        // 判断订单状态
        if (ordersModel == null || ordersModel.getOrderPrice() <= 0
                || !OrderStateEnum.WAIT_PAYMENT.getCode().equals(ordersModel.getOrderState())
                || !RefundStateEnum.NO_REFUND.getCode().equals(ordersModel.getRefundState())) {
            return ResultModel.fail("无效支付信息，请联系客户~！");
        }
        try {
            // 删除之前redis里缓存的订单prepayId
            redisUtil.remove(RedisCode.getPrepayId(ordersModel.getOrdersNo()));
            // 获取之前redis保存下单商品信息
            OrderNoEntity entity = redisUtil.get(RedisCode.getUserOrderKey(ordersModel.getOrdersNo()));
            if(entity == null) {
                entity = new OrderNoEntity();
                entity.setOrdersId(request.getOrdersId());
                entity.setUserId(request.getId().intValue());
                entity.setMoney(ordersModel.getOrderPrice());
                entity.setCompanyId(ordersModel.getCompanyId());
                entity.setAssembleId(ordersModel.getAssembleId());
            }
            // redis保存下单商品信息
            redisUtil.set(RedisCode.getUserOrderKey(ordersModel.getOrdersNo()), entity, 30, TimeUnit.MINUTES);
            // 查询用户openId信息
            UserModel userModel = userMapper.selectByPrimaryKey(request.getId().intValue());
            // 调用微信支付生产二维码接口
            Map<String, String> wxData = wxPayService.wxPay(body, ordersModel.getOrdersNo(), String.valueOf(ordersModel.getOrderPrice()), userModel.getOpenId(), request.getIp(), request.getOrdersId(), request.getCompanyKey());
            // 微信生成的预支付会话标识，用于后续接口调用中使用（微信推送模板），该值有效期为2小时
            redisUtil.set(RedisCode.getPrepayId(ordersModel.getOrdersNo()), wxData.get("prepay_id"), 120, TimeUnit.MINUTES);
            return ResultModel.success(wxData);
        } catch (GoPayException gpe) {
            log.info(gpe.getMessage());
            return ResultModel.fail(gpe.getMessage());
        } catch (Exception e) {
            log.info("支付请求失败：" + e.getMessage());
            return ResultModel.fail(e.getMessage());
        }
    }

    /**
     * 校验下单的商品数据
     * @param ordersRequest
     * @return
     */
    public ResultModel validationOrderParames(OrdersRequest ordersRequest){
        log.info("校验下单的商品数据:{}",JSON.toJSONString(ordersRequest));
        if (ordersRequest == null || ordersRequest.getOrderinfoRequestList() == null || ordersRequest.getOrderinfoRequestList().size() <= 0) {
            return ResultModel.checkParamFail();
        }
        if (ordersRequest.getAddressId() == null) {
            return ResultModel.fail("请选择收货地址~！");
        }
        // 下单商品
        List<GoodSpecModel> list = new ArrayList<>();
        // 订单总金额
        Integer orderPrice = 0;
        //
        Set<Integer> set = new HashSet<>();
        for(OrderinfoRequest request : ordersRequest.getOrderinfoRequestList()){
            GoodSpecModel model = goodSpecMapper.getSpecNumPrice(request.getSpecId());
            if(model == null){
                return ResultModel.fail("商品信息失效~！");
            }
            if(model.getSpecNum() == 0 || model.getSpecNum() < request.getNum()){
                return ResultModel.fail("商品库存不足~!");
            }
            if(request.getNum() > 0) {
                model.setSpecId(request.getSpecId());
                model.setGoodsId(request.getGoodsId());
                model.setNum(request.getNum());
                model.setCardId(request.getCardId());
                model.setForwardId(request.getForwardId());
                model.setLevel(request.getLevel());
                model.setShopCartId(request.getShopCartId());
                list.add(model);
                orderPrice += model.getPrice() * request.getNum();
                set.add(model.getCompanyId());
            }
        }
        if(set.size() != 1){
            return ResultModel.fail("请选择相同店铺的商品进行下单~！");
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("list", list);
        map.put("orderPrice", orderPrice);
        map.put("companyId", set.iterator().next());
        return ResultModel.success(map);
    }

    /**
     * 校验下单的商品数据(拼团版本)
     * @param ordersRequest
     * @return
     */
    public ResultModel validationOrderParamesNew(OrdersRequest ordersRequest){
        log.info("校验下单的商品数据:{}",JSON.toJSONString(ordersRequest));
        if (ordersRequest == null || ordersRequest.getOrderinfoRequestList() == null || ordersRequest.getOrderinfoRequestList().size() <= 0) {
            return ResultModel.checkParamFail();
        }
        if (ordersRequest.getAddressId() == null) {
            return ResultModel.fail("请选择收货地址~！");
        }
        // 下单商品
        List<GoodSpecModel> list = new ArrayList<>();
        // 订单总金额
        Integer orderPrice = 0;
        Set<Integer> set = new HashSet<>();
        for(OrderinfoRequest request : ordersRequest.getOrderinfoRequestList()){
            GoodSpecModel model = goodSpecMapper.getSpecNumPrice(request.getSpecId());
            if(model == null){
                return ResultModel.fail("商品信息失效~！");
            }
            if(ordersRequest.getAssembleId() != null) {
                if (model.getAssembleNum() == 0 || model.getAssembleNum() < request.getNum()) {
                    return ResultModel.fail("商品拼团库存不足~!");
                }
            }else{
                if (model.getSpecNum() == 0 || model.getSpecNum() < request.getNum()) {
                    return ResultModel.fail("商品库存不足~!");
                }
            }
            if(request.getNum() != null && request.getNum() > 0) {
                model.setSpecId(request.getSpecId());
                model.setGoodsId(request.getGoodsId());
                model.setNum(request.getNum());
                model.setCardId(request.getCardId());
                model.setForwardId(request.getForwardId());
                model.setLevel(request.getLevel());
                model.setShopCartId(request.getShopCartId());
                list.add(model);
                // 拼团价格
                if(ordersRequest.getAssembleId() != null) {
                    orderPrice += model.getAssemblePrice() * request.getNum();
                }else {
                    orderPrice += model.getPrice() * request.getNum();
                }
                set.add(model.getCompanyId());
            }
        }
        if(set.size() != 1){
            return ResultModel.fail("请选择相同店铺的商品进行下单~！");
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("list", list);
        map.put("orderPrice", orderPrice);
        map.put("companyId", set.iterator().next());
        return ResultModel.success(map);
    }



    @Override
    public ResultModel refundOrder(OrdersRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        OrdersModel model = new OrdersModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        // 1未申请，2退款申请中，3退款成功
        model.setRefundState(RefundStateEnum.REFUND_APPLY.getCode());
        if (ordersMapper.updateByPrimaryKeySelective(model) > 0) {
            // 微信推送 退款申请消息
            List<WxNoticeEntity> listMap = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
                setType(1);
                setOrdersId(request.getOrdersId());
            }});
            for (int i = 0; i < listMap.size(); i++) {
                WxNoticeEntity entity = listMap.get(i);
                String[] fillData = {entity.getOrdersNo(), getDay(), getLimitGoodsName(entity.getGoodsName()), getMoneyString(entity.getMoney()) + "元", entity.getRefundRemark()};
                wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.REFUND_APPLY.getCode(), fillData, LoginEnum.CRM.getAccountType(),entity.getCrmCompanyId());
            }
            return ResultModel.success("申请成功");
        }
        return ResultModel.fail("申请失败");
    }

    @Override
    public ResultModel backRefundState(OrdersRequest ordersRequest) {
        OrdersModel ordersModel = new OrdersModel();
        if (ordersRequest != null) {
            BeanUtils.copyProperties(ordersRequest, ordersModel);
        }
        // 1未申请，2退款申请中，3退款成功
        ordersModel.setRefundState(RefundStateEnum.NO_REFUND.getCode());
        r = ordersMapper.updateByPrimaryKeySelective(ordersModel);
        if (r > 0) {
            return ResultModel.success("撤销成功");
        }
        return ResultModel.fail("撤销失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<String> shopcartOrder(ShopcartRequest shopcartRequest) {
        log.info("购物车下单：{}", JSON.toJSONString(shopcartRequest));
        String message = null;
        try {
            List<ShopcartModel> list = shopcartMapper.selectOrderInfoGroup(shopcartRequest.getShopCartIds().split(","));
            List<ShopcartModel> modelList = shopcartMapper.selectOrderInfo(shopcartRequest.getShopCartIds().split(","));
            if (list == null || list.size() <= 0) {
                log.info("商品信息异常，请稍后重试！", shopcartRequest);
                return ResultModel.fail("订单异常，请稍后重试!");
            }
            if(list.size() > 1){
                log.info("只能选择同一公司商品下单！", shopcartRequest);
                return ResultModel.fail("只能选择同一公司商品下单~!");
            }
            StringBuffer str = new StringBuffer();
            int allMoney = 0;
            for (ShopcartModel model : list) {
                // 在添加总订单表
                OrdersModel ordersModel = new OrdersModel();
                ordersModel.setUserId(shopcartRequest.getId().intValue());
                ordersModel.setPayType(1);
                ordersModel.setCreateTime(currentDate());
                ordersModel.setOrderState(OrderStateEnum.WAIT_PAYMENT.getCode());
                ordersModel.setRefundState(RefundStateEnum.NO_REFUND.getCode());
                ordersModel.setCompanyId(model.getCompanyId());
                ordersModel.setOrdersNo(getOrderNo());
                ordersModel.setDeliveryType(1);
                ordersModel.setDeliveryState(1);
                r = ordersMapper.insertSelective(ordersModel);
                if (r <= 0) {
                    log.info("下单失败，网络异常！", shopcartRequest);
                    message = "下单失败，网络异常";
                    throw new RuntimeException();
                }
                str.append(ordersModel.getOrdersId() + ",");
                int money = 0;
                for (ShopcartModel obj : modelList) {
                    if (!model.getCompanyId().equals(obj.getCompanyId())) {
                        continue;
                    }
                    // 判断商品规格库存--》商品库存：购买数量
                    if (obj.getSpecNum() < obj.getNum()) {
                        message = "下单失败，库存不足";
                        throw new RuntimeException();
                    }
                    // 统计金额 += 商品数量 * 商品价格
                    money += obj.getNum() * obj.getPrice();
                    allMoney += obj.getNum() * obj.getPrice();
                    // 添加订单明细表
                    OrderinfoModel orderinfoModel = new OrderinfoModel();
                    // 总订单id
                    orderinfoModel.setOrdersId(ordersModel.getOrdersId());
                    //商品单价
                    orderinfoModel.setPrice(obj.getPrice());
                    //订单数量
                    orderinfoModel.setNum(obj.getNum());
                    // 订单价格
                    orderinfoModel.setAllPrice(obj.getNum() * obj.getPrice());
                    // 商品id
                    orderinfoModel.setGoodsId(obj.getGoodsId());
                    // 商品规格id
                    orderinfoModel.setSpecId(obj.getSpecId());
                    orderinfoModel.setCreateTime(currentDate());
                    orderinfoModel.setCardId(obj.getCardId());
                    orderinfoModel.setForwardId(obj.getForwardId());
                    orderinfoMapper.insertSelective(orderinfoModel);
                }
                // 保存订单金额
                OrdersModel ordersModel1 = new OrdersModel();
                ordersModel1.setOrderPrice(money);
                ordersModel1.setOrdersId(ordersModel.getOrdersId());
                ordersMapper.updateByPrimaryKeySelective(ordersModel1);
                // 发送新订单微信推送提醒
                List<WxNoticeEntity> listMap = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
                    setType(1);
                    setOrdersId(ordersModel.getOrdersId());
                }});
                if (listMap != null && listMap.size() > 0) {
                    for (int i = 0; i < listMap.size(); i++) {
                        WxNoticeEntity entity = listMap.get(i);
                        String[] fillData = {ordersModel.getOrdersNo(), getLimitGoodsName(entity.getGoodsName()), getMoneyString(money) + "元", getDay(), entity.getReceiveName()};
                        wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.NEW_ORDER.getCode(), fillData, LoginEnum.CRM.getAccountType(),entity.getCrmCompanyId());
                    }
                }
            }
            // 金额校验
            if (allMoney != shopcartRequest.getMoney()) {
                message = "下单失败，金额校验异常！";
                throw new RuntimeException();
            }
            // 删除以下单的购物车
            shopcartMapper.deleteShopcart(shopcartRequest.getShopCartIds().split(","));
            return ResultModel.success(str.toString());
        } catch (RuntimeException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.info(message, shopcartRequest);
            return ResultModel.fail(message);
        } catch (Exception e) {
            log.info("网络异常，请稍后在试!", shopcartRequest);
            return ResultModel.fail("网络异常，请稍后在试!");
        }
    }

    @Override
    public ResultModel updateOrderState(OrdersRequest request) {
        if (request == null || request.getOrderState() == null || request.getOrdersId() == null) {
            return ResultModel.checkParamFail();
        }
        OrdersModel model = new OrdersModel();
        model.setOrdersId(request.getOrdersId());
        model.setOrderState(request.getOrderState());
        r = ordersMapper.updateOrderState(model);
        if (r > 0) {
            // 用户确认收货
            if(OrderStateEnum.COMPLETE.getCode().equals(request.getOrderState())) {
                /** 商品订单完成后提成佣金和转账到公司拥有人(3.2前版本) */
                companyRoyalty(request.getOrdersId(), request.getIp(), request.getCompanyKey());
                // 分销金额提成 (确认收货时调用) （3.2后版本迭代）
                //companyRoyaltyNew(request.getOrdersId(), request.getIp(), request.getCompanyKey());
            }
            // 微信推送 交易取消消息
            List<WxNoticeEntity> listMap = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
                setType(1);
                setOrdersId(request.getOrdersId());
            }});
            listMap.forEach(entity -> {
                {
                    String[] fillData = {entity.getOrdersNo(), getLimitGoodsName(entity.getGoodsName()), getMoneyString(entity.getMoney()) + "元", OrderStateEnum.getMessage(request.getOrderState()), entity.getRemark()};
                    wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.ORDER_STATE_CRM.getCode(), fillData, LoginEnum.CRM.getAccountType(),entity.getCrmCompanyId());
                }
            });
            return ResultModel.success("操作成功");
        }
        return ResultModel.fail("操作失败");
    }

    @Override
    public ResultModel doReminder(OrdersRequest request) {
        if (request == null || request.getOrdersId() == null || request.getId() == null) {
            return ResultModel.checkParamFail();
        }
        ResultModel resultModel = getDoReminder(request);
        if(!resultModel.isSuccess()){
            return resultModel;
        }
        // 微信推送 发货提醒消息
        List<WxNoticeEntity> listMap = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
            setType(1);
            setOrdersId(request.getOrdersId());
        }});
        listMap.forEach(entity -> {
            {
                String[] fillData = {entity.getOrdersNo(), getLimitGoodsName(entity.getGoodsName()), getMoneyString(entity.getMoney()) + "元", entity.getPayDate(), entity.getRemark()};
                wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.ORDER_DELIVER.getCode(), fillData, LoginEnum.CRM.getAccountType(),entity.getCrmCompanyId());
            }
        });
        return ResultModel.success();
    }

    public ResultModel getDoReminder(OrdersRequest request){

        OrderNoEntity entity = redisUtil.get(RedisCode.getDoReminder(request.getId().intValue(),request.getOrdersId()));
        if(entity != null){
            return ResultModel.fail("已提醒发货，请耐心等待~！");
        }
        // redis用户提醒发货记录
        entity = new OrderNoEntity();
        entity.setOrdersId(request.getOrdersId());
        // java 1.8 计算当天剩余时间
        LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight);
        redisUtil.set(RedisCode.getDoReminder(request.getId().intValue(),request.getOrdersId()), entity, seconds, TimeUnit.SECONDS);
        return ResultModel.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel anotherOrder(OrdersRequest request){
        log.info("再来一单：{}", JSON.toJSONString(request));
        if (request == null || request.getOrdersId() == null) {
            return ResultModel.checkParamFail();
        }
        List<OrdersModel> list = ordersMapper.selectAnotherOrder(request.getOrdersId());
        if (list == null || list.size() <= 0) {
            log.info("操作失败，订单信息异常：{}", request.getOrdersId());
            return ResultModel.fail("操作失败，订单信息异常！");
        }
        try {
            // 在添加订单表
            OrdersModel ordersModel = new OrdersModel();
            // 用户ID
            ordersModel.setUserId(request.getId().intValue());
            // 默认线上支付
            ordersModel.setPayType(1);
            ordersModel.setCreateTime(new Date());
            // 订单状态（1待付款，2待发货，3待收货，4已完成，5交易取消，6退款成功）
            ordersModel.setOrderState(OrderStateEnum.WAIT_PAYMENT.getCode());
            // 1未申请，2退款申请中，3退款成功
            ordersModel.setRefundState(RefundStateEnum.NO_REFUND.getCode());
            ordersModel.setCompanyId(list.get(0).getCompanyId());
            // 订单号
            ordersModel.setOrdersNo(getOrderNo());
            // 配送方式
            ordersModel.setDeliveryType(1);
            // 配送方式
            ordersModel.setDeliveryState(1);
            ordersMapper.insertSelective(ordersModel);
            int money = 0;
            int ii = 0;
            for (OrdersModel model : list) {
                if (goodsMapper.selectGoodsCount(model.getGoodsId()) <= 0) {
                    ii++;
                } else {
                    // 判断商品规格库存
                    GoodSpecModel goodSpecModel = goodSpecMapper.selectByPrimaryKey(model.getSpecId());
                    if (goodSpecModel != null && goodSpecModel.getSpecNum() >= model.getNum()) {
                        // 添加订单明细表
                        money += goodSpecModel.getPrice() * model.getNum();
                        OrderinfoModel orderinfoModel = new OrderinfoModel();
                        // 订单id
                        orderinfoModel.setOrdersId(ordersModel.getOrdersId());
                        orderinfoModel.setGoodsId(goodSpecModel.getGoodsId());
                        orderinfoModel.setSpecId(goodSpecModel.getSpecId());
                        orderinfoModel.setNum(model.getNum());
                        orderinfoModel.setPrice(goodSpecModel.getPrice());
                        // 订单价格
                        orderinfoModel.setAllPrice(goodSpecModel.getPrice() * model.getNum());
                        orderinfoModel.setCreateTime(new Date());
                        orderinfoModel.setCardId(model.getCardId());
                        orderinfoMapper.insertSelective(orderinfoModel);
                    }
                }
            }
            // 商品信息全部失效
            if (ii == list.size()) {
                //throw new Exception();
                return ResultModel.fail("商品信息失效！");
            }
            OrdersModel ordersModel1 = new OrdersModel();
            ordersModel1.setOrderPrice(money);
            ordersModel1.setOrdersId(ordersModel.getOrdersId());
            ordersMapper.updateByPrimaryKeySelective(ordersModel1);
            // 发送新订单微信推送提醒
            List<WxNoticeEntity> listMap = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
                setType(1);
                setOrdersId(ordersModel.getOrdersId());
            }});
            if (listMap != null && listMap.size() > 0) {
                for (int i = 0; i < listMap.size(); i++) {
                    WxNoticeEntity entity = listMap.get(i);
                    String[] fillData = {ordersModel.getOrdersNo(), getLimitGoodsName(entity.getGoodsName()), getMoneyString(money) + "元", getDay(), entity.getReceiveName()};
                    wxMessageService.sendTemplate(entity.getCrmOpenId(), entity.getCrmFormId(), WxNoticeEnums.NEW_ORDER.getCode(), fillData, LoginEnum.CRM.getAccountType(), entity.getCrmCompanyId());
                }
            }
            return ResultModel.success("操作成功");
        }catch (Exception e){
            log.info("商品信息失效：{}", request.getOrdersId());
            e.printStackTrace();
        }
        return ResultModel.fail();
    }



    @Override
    public ResultModel shopAddCollection(CollectionRequest request) {
        if (request != null) {
            for (String id : request.getItemIds().split(arraySymbol)) {
                CollectionModel collectionModel = new CollectionModel();
                collectionModel.setUserId(request.getId().intValue());
                collectionModel.setItemType(request.getItemType());
                collectionModel.setItemId(Integer.parseInt(id));
                List<CollectionModel> list = collectionMapper.select(collectionModel);
                if (list == null || list.size() <= 0) {
                    collectionModel.setCreateTime(currentDate());
                    collectionMapper.insertSelective(collectionModel);
                }
            }
            return ResultModel.success("保存成功");
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<List<OrdersResponse>> getOrderInfo(OrdersRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        OrdersModel model = new OrdersModel();
        model.setIds(request.getOrdersIds().split(","));
        List<OrdersModel> list = ordersMapper.getOrderInfo(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<OrdersResponse> ordersResponseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                OrdersResponse ordersResponse = new OrdersResponse();
                BeanUtils.copyProperties(obj, ordersResponse);
                ordersResponseList.add(ordersResponse);
            }
        });
        return ResultModel.success(ordersResponseList);
    }

    @Override
    public ResultModel<List<OrdersResponse>> getPayOrderInfo(OrdersRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        OrdersModel model = new OrdersModel();
        model.setIds(request.getOrdersIds().split(","));
        List<OrdersModel> list = ordersMapper.getOrderInfo(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<OrdersResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                OrdersResponse response = new OrdersResponse();
                BeanUtils.copyProperties(obj, response);
                if(obj.getDeliveryTime() != null) {
                    response.setDeliveryTimes(getSurplusDeliveryTime(obj.getDeliveryTime()));
                }
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel<Integer> openOrJoinAssemble(AssembleRequest request) {
        if(request == null || request.getId() == null || request.getGoodsId() == null){
            return ResultModel.checkParamFail();
        }
        GoodsAssembleModel goodsAssembleModel = goodsAssembleMapper.getGoodsAssemble(request.getGoodsId());
        if(goodsAssembleModel == null){
            return ResultModel.fail("该商品未设置拼团配置~！");
        }
        AssembleModel model = new AssembleModel();
        model.setGoodsId(request.getGoodsId());
        model.setUserId(request.getId().intValue());
        Map<String, Object> map = assembleMapper.getJoinAssemble(model);
        if(goodsAssembleModel.getMaxPurchase() <= (int)map.get("orderNum")){
            return ResultModel.fail("单账号最多可购买数:" + goodsAssembleModel.getMaxPurchase() + "; 您已达到上限~！");
        }
        if(request.getAssembleId() != null){
            if(goodsAssembleModel.getJoinRegiment() <= (int)map.get("assembleNum")){
                return ResultModel.fail("单账号最多参团数：" + goodsAssembleModel.getJoinRegiment() + "; 您已达到上限~！");
            }
            if(goodsAssembleModel.getPeopleNum() <= (int)map.get("putAssemble")){
                return ResultModel.fail("成团人数已达到上限~！");
            }
            model.setAssembleId(request.getAssembleId());
        }else{
            Integer openAssembleNum = assembleMapper.getOpenAssembleNum(model);
            if(goodsAssembleModel.getOpenRegiment() <= openAssembleNum){
                return ResultModel.fail("单账号最多开团数：" + goodsAssembleModel.getOpenRegiment() + "; 您已达到上限~！");
            }
            model.setAssembleNum(goodsAssembleModel.getPeopleNum());
            model.setPutAssemble(0);
            model.setIsDel(0);
            model.setCreateTime(currentDate());
            model.setState(0);
            assembleMapper.insertSelective(model);
        }
        return ResultModel.success(model.getAssembleId());
    }
}
